

$(document).ready(function(){
  $('#patchList').tablesorter({
    headers :{
      0 :{sorter:false},
      7 :{sorter:false}
    }
  });
  
    $("#patchList").on("click", " tr td", addInput);
    $('#name').on("click", addInput);
    $(document).on("click", ".deleteInput" ,deleteInput); 
    
    $(document).on("click", '#patchList tbody tr td:nth-last-of-type(1)',deleteTdClick);
    $(document).on("click", "#submitChanges" ,SaveChanges); 
    
    $('#newEntry').click(AddSupClick);
    
    $("#checkAllEntries").change({"class":".deleteEntries"},checkAllCheckboxChanged);  
    $('.deleteEntries').change({"check":"#checkAllEntries","class":".deleteEntries"},classCheckboxChanged);
    

    $('.selectSearch').change(filterChanged);
    
    $('#searchInput').change(filterChanged);
    
      $('#delete').click(deleteChecked);
    
    
});


var entries = Array();
var numberOfBoxes =0;
var ajaxStarted = false;

function deleteTdClick() {
    $(this).empty().append($('<img>')
                .attr({"src":"../design/pictures/loading.gif",
                       "width":"20px",
                       "alt":"loading"}));
    var id = [$(this).attr('patchpanelID')];
    var td = $(this);
    $.post("ajax/patchpanel.php",{function:"delete", patchpanelID:id.toString() }).done(function(data){
      var jsonData=$.parseJSON(data);
      if(jsonData.success === "true")
      {
          if(jsonData.message === "true")
          {
              $(td).closest('tr').fadeTo(400,0,function(){$(this).remove();});
          }else
          {
               $(td).empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"loading"}));
          }
      }
      else
      {
        $(td).empty().append($('<img>')
                .attr({"src":"../design/pictures/delete.png",
                       "width":"20px",
                       "alt":"X"}));
      }
    }).fail(function(){
      $(td).empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
    }).always(function(){
    });
}


function addInput()
{   
              if((typeof($(this).attr('name')) != 'undefined') && ($('input[name="'+$(this).attr('name')+'"]').length < 1))
              {
                    var text = $(this).text();
                    entries[$(this).attr('name')] = text;
                    var name = $(this).attr('name');
                    $(this).text('');      // Inhalt des <td>-Tags löschen
                    $(this).append($("<input>").attr({"name":name, "type":"text", "value":text, "list":$(this).attr('info')}))
                            .append($("<input>").attr({"type":"Button", "value":"Abbruch", "name":"abort", "class":"deleteInput"}));
                    if(numberOfBoxes===0)
                    {
                        $('#submitArea').append($('<input>').attr({"type":"button", "value":"Übernehmen", "name":"submit", "id":"submitChanges"}));
                    }
                    numberOfBoxes++;     
               }            
            }

function deleteInput()
{   
            $(this).prev().replaceWith(entries[$(this).prev().attr('name')]);
            $(this).remove();
            numberOfBoxes--;
            if(numberOfBoxes === 0)
             {
               $('#submitArea').empty();
             }
}

function SaveChanges()  //Saves the changes in the table
{
    $('#submitChanges').replaceWith('<img src="../design/pictures/loading.gif" width="20px" alt="..." />');
    //Replace the submit Button with the load element
    //send an ajax request to the server
    $.post("ajax/patchpanel.php", ($('#update').serialize()+'&'+$.param({function:'update'}))).done(function(data) 
    {
         //change the values in the table
          $('#patchList tr td input').each(function(){
          $(this).next().replaceWith($(this).val());
          $(this).remove();
          numberOfBoxes=0;
          $('#submitArea').empty();
        }); 
    });  
}


function AddSupClick() {
  if(!ajaxStarted)
  {
    ajaxStarted=true;
    $('#newFormTable tbody tr:nth-last-of-type(1) td:nth-child(2)').empty().append($('<img>')
                .attr({"src":"../design/pictures/loading.gif",
                       "width":"20px",
                       "alt":"loading"}));
    
    $.post("ajax/patchpanel.php", ($('#new').serialize() + "&" + $.param({function:"add"}))).done(function(data){
      var jsonData=$.parseJSON(data);
      if(jsonData.success === "true")
      {
          jsonData.message
        $('#newFormTable tbody tr:nth-last-of-type(1) td:nth-child(2)').empty();
        var tr =  '<tr panelid='+ jsonData.message[6]+'>'
                    + '<td><input type="checkbox" name="del[' + jsonData.message[6] + ']" value="" class="deleteEntries"></td>'
                    + '<td name="entry[' + jsonData.message[6] + '][0]" info=\"switchPort\"> '+ jsonData.message[0]+'</td>'
                    + '<td name="entry[' + jsonData.message[6] + '][1]" info=\"switch\" >' + jsonData.message[1] + '</td>'
                    + '<td name="entry[' + jsonData.message[6] + '][2]" info=\"patchName\" >' + jsonData.message[2] + '</td>'
                    + '<td name="entry[' + jsonData.message[6] + '][3]" info=\"roomName\" >' + jsonData.message[3] + '</td>'
                    + '<td name="entry[' + jsonData.message[6] + '][4]" info=\"roomNumber\" >' + jsonData.message[4] + '</td>'
                    + '<td name="entry[' + jsonData.message[6] + '][5]" info=\"levelName\" >' + jsonData.message[5] + '</td>'
                    + '<td patchpanelID="' +jsonData.message[6] +'"> <img src="../design/pictures/delete.png" width="20" alt="X"/></td>'
                    + '</tr>';
        $('#patchList tbody').append(tr);
        $('#newFormTable tbody tr:nth-last-of-type(2) td input').val('');
      }
      else
      {
        $('#newFormTable tbody tr:nth-last-of-type(1) td:nth-child(2)').empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
      }
    }).fail(function(){
      $('#newFormTable tbody tr:nth-last-of-type(1) td:nth-child(2)').empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
    }).always(function(){
      ajaxStarted = false;
    });
  }
}

function classCheckboxChanged(e){
  var allChecked= true;
    $(e.data.class+":visible").each(function(){
     if(!$(this).is(':checked'))
       allChecked = false;
    });
    if(allChecked)
    {
      $(e.data.check).prop('checked',true);
    }
    else
      $(e.data.check).prop('checked',false);
}

function checkAllCheckboxChanged(e){
  if($(this).is(':checked'))
    {
        $(e.data.class+":visible").prop('checked', true);
    }else
    {
        $(e.data.class+":visible").prop('checked', false);
    }
}


function filterChanged(){
  var hiddenTrInRow = 0;
  var searchFieldText =  $('#searchInput').val().trim().toLowerCase();
  var checkInvNumber = $('.selectSearch:checked').attr('id');

  var searchField="";
  switch(checkInvNumber)
  {
      case 'selectSwitchport':
          searchField = 'td:nth-of-type(2)';
      break;
      
      case 'selectSwitch':
          searchField = 'td:nth-of-type(3)';
      break;
      
      case 'selectPatchpanel':
          searchField = 'td:nth-of-type(4)';
      break;
      
      case 'selectRoom':
          searchField = 'td:nth-of-type(5)';
      break;
      
      case 'selectRoomNr':
          searchField = 'td:nth-of-type(6)';
      break;
      
      case 'selectLevel':
          searchField = 'td:nth-of-type(7)';
      break;
  }
  
  $('#devicesList tbody tr.padding').remove();
  
  if(searchFieldText != "")
  {
    $('#patchList tbody tr').show().each(function(){ 
     if($(this).find(searchField).text().trim().toLowerCase().indexOf(searchFieldText) < 0)
      {
        $(this).hide();
        hiddenTrInRow++;
      }
      else
      {
        if((hiddenTrInRow%2)>0)
          $(this).before($('<tr>').attr('class','padding').hide());
        hiddenTrInRow=0;
      }
    });
  }else
  {
    $('#patchList tbody tr').show();
  }
  $('.deleteCheckbox').trigger('change');
}

function deleteChecked()
{
  if(confirm("Wollen Sie die ausgewählten Einträge wirklich löschen?"))
  {
      $('#load').empty().append('<img src="../design/pictures/loading.gif" width="20px" alt="..." />');
      $.post("ajax/patchpanel.php", ($('#update').serialize() + "&" + $.param({function:"deleteChecked"}))).done(function(data){
      var jsonData=$.parseJSON(data);
      if(jsonData.success === "true")
      {
          $.each(jsonData.message, function(i,ID)
          {
              $("#patchList tbody tr[panelID='" + ID + "']").fadeTo(400,0,function(){$(this).remove();});
          });
           $('#load').empty();
      }
      else
      {
          $('#load').empty().append('<img src="../design/pictures/error.png" width="20px" alt="..." />');
      }
    }).fail(function(){
        $('#load').empty().append('<img src="../design/pictures/error.png" width="20px" alt="..." />');
    });
  }
}
